﻿using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DynCRMMessagingIntegration.Workflow
{
    public abstract class BaseCodeActivity : CodeActivity
    {
        protected ITracingService TracingService
        {
            get;
            set;
        }

        protected IWorkflowContext WorkflowContext
        {
            get;
            set;
        }

        protected IOrganizationServiceFactory OrganizationServiceFactory
        {
            get;
            set;
        }

        protected IOrganizationService OrganizationService
        {
            get;
            set;
        }

        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            TracingService = executionContext.GetExtension<ITracingService>();

            if (this.TracingService == null)
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");

            TracingService.Trace("Entered ProcessMessageActivity.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                executionContext.ActivityInstanceId,
                executionContext.WorkflowInstanceId);

            // Create the context
            WorkflowContext = executionContext.GetExtension<IWorkflowContext>();

            if (WorkflowContext == null)
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");

            TracingService.Trace("Workflow Context ready. Correlation Id: {0}, Initiating User: {1}",
                WorkflowContext.CorrelationId,
                WorkflowContext.InitiatingUserId);

            OrganizationServiceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            OrganizationService = OrganizationServiceFactory.CreateOrganizationService(WorkflowContext.UserId);

            TracingService.Trace("Organisation Service Factory and Organisation Service are ready");

            try
            {
                this.ExecuteActivity(executionContext);
            }
            catch (Exception e)
            {
                TracingService.Trace("Exception: {0}", e.Message);
                throw new InvalidPluginExecutionException(e.Message, e);
            }
            finally
            {
                TracingService.Trace("Exiting ProcessMessageActivity.Execute(), Correlation Id: {0}", WorkflowContext.CorrelationId);
            }
            
        }

        protected abstract void ExecuteActivity(CodeActivityContext executionContext);
    }
}
